iT邦幫忙

2024 iThome 鐵人賽

DAY 9
0
Modern Web

API 101:從基礎認識到應用的全方位指南-Swagger/Postman系列 第 9

DAY9. 如何使用 Swagger 編寫 API 文檔

  • 分享至 

  • xImage
  •  

使用 Swagger 自動生成 API 文件 能大大減少手動編寫 API 文檔的時間和錯誤,這也是很多開發團隊選擇使用它的原因。Swagger 提供多種方式來自動生成 API 文檔,特別是對於後端開發者來說,它能直接從代碼中提取 API 定義並生成符合 OpenAPI 規範的文檔。

Swagger 自動化文檔生成流程
選擇適合的 Swagger 工具:

  • Swagger Codegen:
    生成 API 客戶端代碼和服務端代碼,同時能生成 API 文檔。你可以從 OpenAPI 文檔生成代碼,也可以從代碼生成文檔。
  • Swagger Annotations:
    使用編程語言(例如 Java、Node.js、Python 等)的注解,在代碼中嵌入 API 定義。這些注解會自動轉換為 OpenAPI 規範的文檔。
  • SpringFox(Spring Boot 專用):
  • Spring Boot 提供的工具,可以自動掃描 Spring Boot 應用中的控制器,生成 Swagger 文檔。

在代碼中添加注解:
通常,我們可以在 REST API 控制器和方法中添加注解,Swagger 會根據這些注解自動生成 API 文檔。以下是 Java(Spring Boot)使用 Swagger 的一個簡單範例:

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class UserController {

    @Operation(summary = "Get a user by ID", 
               description = "Returns a user object when the given user ID is valid.",
               responses = {
                  @ApiResponse(responseCode = "200", description = "Successful operation",
                        content = @Content(mediaType = "application/json",
                        schema = @Schema(implementation = User.class))),
                  @ApiResponse(responseCode = "404", description = "User not found")
               })
    @GetMapping("/users/{id}")
    public User getUserById(@PathVariable int id) {
        return new User(id, "John Doe");
    }
}

在這個範例中,我們使用了 @Operation 和 @ApiResponse 等注解來定義 API 文檔。這些注解會被自動掃描並轉換為 OpenAPI 規範的 YAML 或 JSON 文檔。


Swagger 自動化文檔生成的具體步驟(以 Spring Boot + SpringFox 為例)

1. 添加依賴:
在 Spring Boot 項目中引入必要的依賴。編輯 pom.xml,加入 Swagger 和 SpringFox 的依賴:

<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-boot-starter</artifactId>
    <version>3.0.0</version>
</dependency>

2. 配置 Swagger:
創建一個 Swagger 配置類,這樣可以告訴 SpringFox 自動掃描 REST 控制器。

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;

@Configuration
public class SwaggerConfig {

    @Bean
    public Docket api() {
        return new Docket(DocumentationType.OAS_30)
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.example.demo"))
                .paths(PathSelectors.any())
                .build();
    }
}

3. 啟動項目: 當啟動 Spring Boot 項目後,Swagger 會自動生成並提供 API 文檔,可以在 /swagger-ui/index.html 路徑上查看。


實踐中的應用範例

  • 範例 1:使用 Spring Boot 自動生成 API 文檔
    假設你有一個簡單的用戶管理系統,你可以將控制器中使用的注解添加到 API 路徑上,然後生成 API 文檔。通過 @Operation、@ApiResponse 等注解來描述每個 API 的行為,Swagger 自動將這些轉換成易讀的文檔。

訪問 Swagger UI 時,會看到 /users 路徑對應的 GET 操作,點擊後可直接測試 API,並顯示回應格式。

  • 範例 2:Node.js 中使用 Swagger
    對於 Node.js,用戶可以使用 swagger-jsdoc 來自動生成文檔,以下是一個簡單的示例:

安裝 swagger-jsdoc 和 swagger-ui-express:

npm install swagger-jsdoc swagger-ui-express

在應用中配置 Swagger:

const swaggerJsdoc = require('swagger-jsdoc');
const swaggerUi = require('swagger-ui-express');
const express = require('express');
const app = express();

const swaggerOptions = {
    swaggerDefinition: {
        openapi: '3.0.0',
        info: {
            title: 'User API',
            version: '1.0.0',
            description: 'API for managing users'
        }
    },
    apis: ['./routes/*.js'], // 指定包含注解的路徑
};

const swaggerDocs = swaggerJsdoc(swaggerOptions);
app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerDocs));

添加 API 注解: 在routes/user.js中:

/**
 * @swagger
 * /users:
 *   get:
 *     summary: Returns a list of users
 *     responses:
 *       200:
 *         description: A JSON array of user names
 *         content:
 *           application/json:
 *             schema:
 *               type: array
 *               items:
 *                 type: string
 */
app.get('/users', (req, res) => {
    res.json(['John', 'Jane', 'Jack']);
});

啟動應用後,Swagger UI 自動生成可視化文檔,並能通過 /api-docs 路徑查看文檔。

通過使用 Swagger 自動化文檔生成流程,開發者可以輕鬆地在代碼中嵌入 API 定義,並隨時生成最新的 API 文檔。這不僅節省了手動編寫和更新文檔的時間,還能保證 API 文檔與代碼保持同步,非常適合團隊合作和敏捷開發流程。在實踐中,無論是 Java、Node.js 還是其他語言,都有相應的工具和庫可以輕鬆集成 Swagger,提升開發效率。


上一篇
DAY8. 如何使用 Swagger 編寫 API 文檔
下一篇
DAY10. 如何在 Swagger 中進行 API 的安全測試
系列文
API 101:從基礎認識到應用的全方位指南-Swagger/Postman14
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言